const express = require("express")
const router = express.Router()
const journalDB = require("../../../db/journal")
const shareDB = require("../../../db/share")
const userDB = require("../../../db/user")

// 鉴权
router.use((req,res,next)=>{
  if(!req.session.userInfo){
    return res.send({
      code:5,
      mes:"请先登录"
    })
  }
  next()
})

// 用户点赞
router.post("/thumbs",async(req,res)=>{
  try {
    let {aID,type} = req.body
    let {_id} = req.session.userInfo
    if(type === "journal"){
      // 检测是否存在
      let doc = await journalDB.findById(aID)
      if(!doc){
        return res.send({
          mes:"该文章已被发布者删除",
          code:5
        })
      }
      // 检测是否点过赞
      if(doc.likes.includes(_id)){
        // 取消赞
        await journalDB.findByIdAndUpdate(aID,{
          $pull:{
            likes:_id
          }
        })
        //用户取消点赞记录
        await userDB.findByIdAndUpdate(_id,{
          $pull:{
            thumbsJournal:{
              articleID:aID,
            }
          }
        })
        res.send({
          code:0,
          mes:"用户取消点赞"
        })
        return
      }
      // 文章添加点赞
      await journalDB.findByIdAndUpdate(aID,{
        $push:{
          likes:_id
        }
      })
      //用户添加点赞记录
      await userDB.findByIdAndUpdate(_id,{
        $push:{
          thumbsJournal:{
            articleID:aID,
          }
        }
      })
      res.send({
        code:0,
        mes:"点赞成功"
      })
    }else if(type === "share"){
      // 检测是否存在
      let doc = await shareDB.findById(aID)
      if(!doc){
        return res.send({
          mes:"该文章已被发布者删除",
          code:5
        })
      }
      // 检测是否点过赞
      if(doc.likes.includes(_id)){
        // 取消赞
        await shareDB.findByIdAndUpdate(aID,{
          $pull:{
            likes:_id
          }
        })
        //用户取消点赞记录
        await userDB.findByIdAndUpdate(_id,{
          $pull:{
            thumbsShare:{
              articleID:aID,
            }
          }
        })
        res.send({
          code:0,
          mes:"用户取消点赞"
        })
        return
      }
      // 文章添加点赞
      await shareDB.findByIdAndUpdate(aID,{
        $push:{
          likes:_id
        }
      })
      //用户添加点赞记录
      await userDB.findByIdAndUpdate(_id,{
        $push:{
          thumbsShare:{
            articleID:aID,
          }
        }
      })
      res.send({
        code:0,
        mes:"点赞成功"
      })
    }
  } catch (error) {
    res.send({
      code:5,
      mes:"服务器异常，前稍后再试"
    })
  }
})

// 用户收藏
router.post("/collection",async(req,res)=>{
  try {
    let {aID,type} = req.body
    let {_id} = req.session.userInfo
    if(type === "journal"){
      // 检测是否存在
      let doc = await journalDB.findById(aID)
      if(!doc){
        return res.send({
          mes:"该文章已被发布者删除",
          code:5
        })
      }
      // 检测是否已经收藏
      if(doc.collections.includes(_id)){
        // 取消赞
        await journalDB.findByIdAndUpdate(aID,{
          $pull:{
            collections:_id
          }
        })
        //用户取消点赞记录
        await userDB.findByIdAndUpdate(_id,{
          $pull:{
            collectionJournal:{
              articleID:aID,
            }
          }
        })
        res.send({
          code:0,
          mes:"已移除收藏"
        })
        return
      }
      // 文章添加点赞
      await journalDB.findByIdAndUpdate(aID,{
        $push:{
          collections:_id
        }
      })
      //用户添加点赞记录
      await userDB.findByIdAndUpdate(_id,{
        $push:{
          collectionJournal:{
            articleID:aID,
          }
        }
      })
      res.send({
        code:0,
        mes:"收藏成功,可前往个人档中收藏中查看"
      })
    }else if(type === "share"){
      // 检测是否存在
      let doc = await shareDB.findById(aID)
      if(!doc){
        return res.send({
          mes:"该文章已被发布者删除",
          code:5
        })
      }
      // 检测是否收藏
      if(doc.collections.includes(_id)){
        // 取消收藏
        await shareDB.findByIdAndUpdate(aID,{
          $pull:{
            collections:_id
          }
        })
        //用户取消收藏记录
        await userDB.findByIdAndUpdate(_id,{
          $pull:{
            collectionShare:{
              articleID:aID,
            }
          }
        })
        res.send({
          code:0,
          mes:"已移除收藏"
        })
        return
      }
      // 文章添加收藏
      await shareDB.findByIdAndUpdate(aID,{
        $push:{
          collections:_id
        }
      })
      //用户添加点赞记录
      await userDB.findByIdAndUpdate(_id,{
        $push:{
          collectionShare:{
            articleID:aID,
          }
        }
      })
      res.send({
        code:0,
        mes:"收藏成功，可前往个人档中收藏中查看"
      })
    }
  } catch (error) {
    res.send({
      code:5,
      mes:"服务器异常，请稍后再试"
    })
  }
})

// 用户浏览记录
router.post("/record",async(req,res)=>{
  try {
    let {aID,type} = req.body
    let {_id} = req.session.userInfo 
    if(type === "journal"){
      // 检测是否存在
      let doc = await journalDB.findById(aID)
      if(!doc){
        return res.send({
          mes:"该文章已被发布者删除",
          code:5
        })
      }
      let user = await userDB.findById(_id)
      // 检测用户是否浏览过该文章
      user.recordJournal.forEach(async item=>{
        if(item.articleID+"" == aID){
          await userDB.findByIdAndUpdate(_id,{
            $pull:{
              recordJournal:{
                articleID:aID
              }
            }
          })
        }
      })
      // 用户添加浏览记录
      await userDB.findByIdAndUpdate(_id,{
        $push:{
          recordJournal:{
            articleID:aID,
          }
        }
      })
      res.send({
        code:0,
        mes:"历史记录"
      })
    }else if(type === "share"){
      // 检测是否存在
      let doc = await shareDB.findById(aID)
      if(!doc){
        return res.send({
          mes:"该文章已被发布者删除",
          code:5
        })
      }
      let user = await userDB.findById(_id)
      // 检测用户是否浏览过该文章
      user.recordShare.forEach(async item=>{
        if(item.articleID+"" == aID){
          await userDB.findByIdAndUpdate(_id,{
            $pull:{
              recordShare:{
                articleID:aID
              }
            }
          })
        }
      })
      //用户添加浏览记录
      await userDB.findByIdAndUpdate(_id,{
        $push:{
          recordShare:{
            articleID:aID,
          }
        }
      })
      res.send({
        code:0,
        mes:"历史记录"
      })
    }
  } catch (error) {
    res.send({
      code:5,
      mes:"服务器异常，请稍后再试"
    })
  }
})

// 获取用户浏览记录
router.get("/getRecord",async(req,res)=>{
  try {
    let {_id} = req.session.userInfo
    let doc = await userDB.findById(_id)
    .populate("recordJournal.articleID")
    .populate("recordShare.articleID")
    let recor = []
    if(doc.recordJournal.length){
      recor.push(...doc.recordJournal)
    }
    if(doc.recordShare.length){
      recor.push(...doc.recordShare)
    }
    let newArr = []
    for(let i=0;i<recor.length;i++){
      for(var j=i; j<recor.length;j++){
        if(recor[i].date<recor[j].date){
          let min=recor[i];
          recor[i]=recor[j];
          recor[j]=min;
        }
      }
      newArr.push(recor[i])
    }
    res.send({
      code:0,
      mes:"用户最近的浏览记录",
      data:newArr
    })
  } catch (error) {
    res.send({
      code:5,
      mes:"服务器异常，轻稍后再试"
    })
  }
})

// 获取用户点赞记录
router.get("/getThumbs",async(req,res)=>{
  try {
    let {_id} = req.session.userInfo
    let doc = await userDB.findById(_id)
    .populate("thumbsJournal.articleID")
    .populate("thumbsShare.articleID")
    let newArr = []
    if(doc.thumbsJournal){
      newArr.push(...doc.thumbsJournal)
    }
    if(doc.thumbsShare){
      newArr.push(...doc.thumbsShare)
    }
    let thumbs = []
    for(let i=0;i<newArr.length;i++){
      for(var j=i; j<newArr.length;j++){
        if(newArr[i].date<newArr[j].date){
          let min=newArr[i];
          newArr[i]=newArr[j];
          newArr[j]=min;
        }
      }
      thumbs.push(newArr[i])
    }
    res.send({
      code:0,
      data:thumbs,
      mes:"用户点赞记录"
    })
  } catch (error) {
    res.send({
      code:5,
      mes:"服务器异常，请稍后再试"
    })
  }
})

// 获取用户收藏记录
router.get("/getCollection",async(req,res)=>{
  try {
    let {_id} = req.session.userInfo
    let doc = await userDB.findById(_id)
    .populate("collectionJournal.articleID")
    .populate("collectionShare.articleID")
    let newArr = []
    if(doc.collectionJournal){
      newArr.push(...doc.collectionJournal)
    }
    if(doc.collectionShare){
      newArr.push(...doc.collectionShare)
    }
    let thumbs = []
    for(let i=0;i<newArr.length;i++){
      for(var j=i; j<newArr.length;j++){
        if(newArr[i].date<newArr[j].date){
          let min=newArr[i];
          newArr[i]=newArr[j];
          newArr[j]=min;
        }
      }
      thumbs.push(newArr[i])
    }
    res.send({
      code:0,
      data:thumbs,
      mes:"用户点赞记录"
    })
  } catch (error) {
    res.send({
      code:5,
      mes:"服务器异常，请稍后再试"
    })
  }
})

module.exports = router